# $Id: ipc.py 9227e81e919a 2012/08/27 15:49:57 pgurumur $
# Copyright (c) 2012 Prabhu Gurumurthy <pgurumur@gmail.com>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

__version__  = "$Revision: 9227e81e919a $"
__author__   = "$Author: pgurumur $"
__modified__ = "$Date: 2012-08-27 15:49:57Z $"

import os
import SocketServer
import socket
import struct

import stdlib
import log
import sql

class TrapHandler(SocketServer.StreamRequestHandler):
   def __init__(self, request, client_address, server):
      self.log = log.StreamLog(stdlib.my_name(self))
      self._server = server
      SocketServer.StreamRequestHandler.__init__(self, request,
            client_address, server)

   def bgp(self, host, peer, state):
      if self._sql:
         bgp = self._sql["bgppeering"]
         device = self._sql["device"]
         ipblock = self._sql["ipblock"]
         entity = self._sql["entity"]

         for (address, dev) in bgp.q.filter(bgp.bgppeeraddr == peer).filter(
               bgp.monitored == 1).values(bgp.bgppeeraddr, bgp.device):
            devip = ipblock.q.filter(ipblock.id == device.q.filter(
               device.id == dev).filter(device.monitored == 1).value(
                  device.snmp_target)).value(ipblock.address)
            if devip:
               devip = socket.inet_ntoa(struct.pack(">L", devip))
            print address, devip

   def setup(self):
      if self._server:
         try:
            self._sql = self.server.dbhandle()
         except:
            self.log("cannot get SQL handle!")
            self._sql = None

   def finish(self):
      if self._sql:
         self._sql.close()

   def handle(self):
      request = self.rfile.readline()
      if request:
         (command, host, peer, state) = request.split(" ")
         if command == "bgp":
            self.bgp(self, host, peer, state)


